package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.UserService;
import com.cskaoyan.market.service.UserServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.AnnotationUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName AdminUserController
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/3/14 14:57
 * @Version V1.0
 **/
@WebServlet("/admin/user/*")
public class AdminUserController extends HttpServlet {

    UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/user/", "");
        if("list".equals(op)){
            list(req, resp);
        }
    }

    // ?page=1&limit=20&username=1&mobile=3&userId=&sort=add_time&order=desc
    //1.接收请求参数
    //2.处理业务逻辑
    //3.返回结果=-----抓包
    //controller:接收请求、接收参数、校验、调用模型、返回结果
    // service: 处理具体的业务逻辑，负责去调用一个一个的mapper方法
    // mapper:单独去提供一个一个的方法调用，比如CRUD等功能
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String username = req.getParameter("username");
        String mobile = req.getParameter("mobile");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        Integer pageParam = null;
        Integer limitParam = null;

        try {
            pageParam = Integer.parseInt(page);
            limitParam = Integer.parseInt(limit);
        }catch (Exception e){
            //如果是异常，则直接返回一个错误的信息
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //因为ResponseUtils里面包含errno、errmsg、data等属性，我们只需要去填充data数据即可
        //所以我们这里调用模型的代码时service代码时，最好能够返回就是data需要的数据
        //TODO
        List<MarketUser> userList = userService.list(pageParam,limitParam,username,mobile,sort,order);
        Object o = ResponseUtil.okList(userList);
        resp.getWriter().println(JacksonUtil.writeValueAsString(o));
    }
}
